package com.gobo.jinghuimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gobo.common.constant.ProductConstant;
import com.gobo.jinghuimall.product.dao.AttrAttrgroupRelationDao;
import com.gobo.jinghuimall.product.dao.AttrGroupDao;
import com.gobo.jinghuimall.product.dao.CategoryDao;
import com.gobo.jinghuimall.product.entity.AttrAttrgroupRelationEntity;
import com.gobo.jinghuimall.product.entity.AttrGroupEntity;
import com.gobo.jinghuimall.product.service.CategoryService;
import com.gobo.jinghuimall.product.vo.AttrRespon;
import com.gobo.jinghuimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gobo.common.utils.PageUtils;
import com.gobo.common.utils.Query;

import com.gobo.jinghuimall.product.dao.AttrDao;
import com.gobo.jinghuimall.product.entity.AttrEntity;
import com.gobo.jinghuimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttrVo(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        //保存属性的基本信息
        this.save(attrEntity);
        if (attrEntity.getAttrType() == ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()) {
            Long attrGroupId = attrVo.getAttrGroupId();
            Long attrId = attrEntity.getAttrId();
            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrgroupRelationEntity.setAttrGroupId(attrGroupId);
            attrgroupRelationEntity.setAttrId(attrId);
            attrgroupRelationDao.insert(attrgroupRelationEntity);
        }
    }

    /**
     * @param params
     * @param catelogId
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String attrType) {
        IPage<AttrEntity> page = null;
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrTypeEnum.ATTR_TYPE_SALE.getCode());
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            attrEntityQueryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        if (catelogId != 0) {
            attrEntityQueryWrapper.eq("catelog_id", catelogId);
        }
        page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespon> attrRespons = records.stream().map((attrEntity) -> {
            AttrRespon attrRespon = new AttrRespon();
            BeanUtils.copyProperties(attrEntity, attrRespon);
            //查询属性分组的名称以及分类的名称
            if (attrEntity.getAttrType() == ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()) {
                Long attrId = attrEntity.getAttrId();
                AttrAttrgroupRelationEntity attrgroupRelationEntity = attrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
                if (attrgroupRelationEntity!=null){
                    Long attrGroupId = attrgroupRelationEntity.getAttrGroupId();
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    attrRespon.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            //查询分类
            attrRespon.setCatelogName(categoryDao.selectById(attrEntity.getCatelogId()).getName());
            return attrRespon;
        }).collect(Collectors.toList());

        pageUtils.setList(attrRespons);
        return pageUtils;
    }

    /**
     * 07、查询属性详情
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrRespon getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespon attrRespon = new AttrRespon();
        BeanUtils.copyProperties(attrEntity, attrRespon);
        //分组信息
        if (attrEntity.getAttrType()==ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrgroupRelationEntity = attrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (attrgroupRelationEntity!=null){
                Long attrGroupId = attrgroupRelationEntity.getAttrGroupId();
                attrRespon.setGroupName(attrGroupDao.selectById(attrGroupId).getAttrGroupName());
                attrRespon.setAttrGroupId(attrGroupId);
            }
        }
        //分类信息
        attrRespon.setCatelogPath(categoryService.getCatelogPath(attrEntity.getCatelogId()));
        return attrRespon;
    }

    /**
     * 更新属性信息
     *
     * @param attrVo
     */
    @Override
    @Transactional
    public void updateAttrVo(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);
        //更新属性 属性分组的关联关系表中的数据  只有是基本属性时才会进行修改分组关联信息
        if (attrEntity.getAttrType()==ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrgroupRelationEntity.setAttrId(attrVo.getAttrId());
            attrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            Integer count = attrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrgroupRelationEntity.getAttrId()));
            if (count > 0) {
                //含有数据进行更新
                attrgroupRelationDao.update(attrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrgroupRelationEntity.getAttrId()));
            } else {
                //插入数据
                attrgroupRelationDao.insert(attrgroupRelationEntity);
            }
        }
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {

       return   baseMapper.selectSearchAttrs(attrIds);

    }

    @Override
    public PageUtils getNoAttrRelationAttr(Long attrgroupId, Map<String, Object> params) {
        //只能查询到相应分类下的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        List<AttrGroupEntity> attrGroupEntityList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        System.out.println(attrGroupEntityList);
        List<Long> attrGroudIdList = attrGroupEntityList.stream().map(obj -> {
            return obj.getAttrGroupId();
        }).collect(Collectors.toList());
        //只能关联其他分组没有关联的属性
        //查询出对应分类下的分组关联信息
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroudIdList));
        //收集关联表中已经关联的属性的ID
        System.out.println(attrAttrgroupRelationEntities);
        List<Long> list = attrAttrgroupRelationEntities.stream().map(obj -> {
            return obj.getAttrId();
        }).collect(Collectors.toList());
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode());
        if (list!=null && list.size()>0){
            attrEntityQueryWrapper.notIn("attr_id", list);
        }
        //查询出不包含以上属性ID的其他属性，必须属于以上的分类
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            attrEntityQueryWrapper.and(obj->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper
        );
        return new PageUtils(page);
    }

}
